<template>
  <div>
    <div class="app-container">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item name="1">
          <template slot="title">
            <i class="el-icon-search" />搜索栏
          </template>
          <div class="head-container">
            <el-form :model="params" :inline="true" size="small" label-width="auto">
              <el-form-item label="分区">
                <el-select v-model="params.division" size="mini" style="width: 180px;" placeholder="请选择" filterable clearable @change="divisionChanged">
                  <el-option v-for="bid in divisions" :key="bid" :label="bid" :value="bid" />
                </el-select>
                <el-select v-model="params.divisionType" size="mini" style="width: 110px;" placeholder="请选择">
                  <el-option label="总耗时" :value="1" />
                  <el-option label="各节点耗时" :value="2" />
                </el-select>
              </el-form-item>
              <el-form-item label="出号日期" label-width="100px" prop="startItemCreateTime">
                <el-date-picker v-model="params.startItemCreateTime" size="mini" type="date" format="MM/dd/yyyy" placeholder="选择开始日期" style="width: 145px;" />
                <el-date-picker v-model="params.endItemCreateTime" size="mini" type="date" format="MM/dd/yyyy" placeholder="选择结束日期" style="width: 145px;" />
              </el-form-item>
              <el-form-item id="buttonID">
                <el-button size="mini" type="primary" icon="el-icon-search" round @click="toQuery">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div id="divFlag" style="padding-left:100px;font-size:16px;"><b>{{ totalTitle }}</b></div>
    <!--<div id="divFlag" style="text-align:center"><b>{{ title }}</b></div>-->
    <div
      id="echarts"
      v-loading="loading"
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      style="width: 90%;height: 460px;left:50px;border:0px solid rgb(100,180,180);"
    />
  </div>
</template>

<script>
import echarts from 'echarts'
import { queryDivision, queryDeptNbrByDivision } from '@/api/lead-time'
import { queryTotalReportByAllDivision, queryDetailReportByAllDivision } from '@/api/lead-time'
import { queryReportByDivision, queryDetailReportByDivision } from '@/api/lead-time'
import { countTotal, countTotalByDevision } from '@/api/lead-time'
import { drawChart, createStackSerie, createSerie } from '@/utils/leadTimeUtils'

import { Message } from 'element-ui'

export default {
  data() {
    return {
      params: { deptNbr: '', startItemCreateTime: null, endItemCreateTime: null, division: '', gmm: '', dmm: '', divisionType: 1 },
      loading: false,
      activeName: '1',
      divisions: [],
      deptNbrs: [],
      nodeLegends: ['采购处理时间', 'Item file审批时间', 'MDA审批时间', 'BPMS审批时间', 'Item file处理时间'],
      divisionLegends: [],
      title: '',
      legends: [],
      series: [],
      xNames: [],
      myChart: null,
      total: 0,
      totalTitle: '',
      unit: '天',
      deptSelectShow: false,
      devisionMap: null,
      deptMap: null
    }
  },
  created() {
    this.$nextTick(() => {
      this.findDivision()
    })
  },
  methods: {
    drawChart,
    createStackSerie,
    createSerie,
    checkItemCreateTime() {

    },
    // 模糊查询
    toQuery() {
      if (this.params.division === null || this.params.division === '') {
        Message({
          message: '请选择分区!',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      if (this.params.startItemCreateTime !== null && this.params.endItemCreateTime === null) {
        Message({
          message: '请选择结束日期!',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      if (this.params.startItemCreateTime === null && this.params.endItemCreateTime !== null) {
        Message({
          message: '请选择开始日期!',
          type: 'warning',
          duration: 2 * 1000
        })
        return
      }
      if (this.myChart != null) {
        this.myChart.dispose()
        this.myChart = null
      }
      this.myChart = echarts.init(document.getElementById('echarts'), 'light')
      if (this.params.division === 'All' && this.params.divisionType === 1) {
        this.getTotal()
        this.drawAllTotal()
      } else if (this.params.division === 'All' && this.params.divisionType === 2) {
        this.getTotal()
        this.drawAllDetail()
      } else if (this.params.division !== 'All' && this.params.divisionType === 1) {
        this.getTotalByDivision()
        this.drawTotalByDivision()
      } else if (this.params.division !== 'All' && this.params.divisionType === 2) {
        this.getTotalByDivision()
        this.drawDetailByDivision()
      }
    },
    getTotal() { // 获取总耗时
      countTotal(this.params).then(res => {
        this.total = 0
        if (res) {
          this.total = res
        }
        this.totalTitle = '平均总耗时: ' + this.total.toFixed(2) + this.unit
      })
    },
    getTotalByDivision() { // 获取各个分区总耗时
      countTotalByDevision(this.params).then(res => {
        this.total = 0
        if (res) {
          this.total = res
        }
        this.totalTitle = '平均总耗时: ' + this.total.toFixed(2) + this.unit
      })
    },
    drawAllTotal() {
      // 统计所有分区总lead time报表
      queryTotalReportByAllDivision(this.params).then(res => {
        // console.log('queryTotalReportByAllDivision:' + JSON.stringify(res))
        if (res) {
          var nameObj = {}
          nameObj.xName = '分区'
          nameObj.yName = '耗时(' + this.unit + ')'
          nameObj.seriesName = '总耗时'
          if (res.length === 0) {
            this.drawChart(this.myChart, nameObj, null, null)
            return
          }
          nameObj.xNames = res[0]
          var series = []
          var serie = this.createSerie(null, res[1], formatter => {
            return formatter.value
          })
          series.push(serie)
          this.drawChart(this.myChart, nameObj, series, formatter => {
            var str = ''
            if (formatter[0].value !== null && formatter[0].value !== '') {
              str += formatter[0].axisValue + ': ' + formatter[0].value.toFixed(2) + this.unit + '<br/>'
            } else {
              str += formatter[0].axisValue + ': - <br/>'
            }
            if (formatter[0].data.depts !== undefined && formatter[0].data.depts !== null) {
              var depts = formatter[0].data.depts
              depts.forEach(item => {
                if (item.name !== null && item.name !== '' && item.name !== '-') {
                  if (item.value !== null) {
                    str += formatter[0].marker + item.name + '部门: ' + item.value.toFixed(2) + this.unit + '<br/>'
                  } else {
                    // str += formatter[0].marker + item.name + '部门: - <br/>'
                  }
                }
              })
            }
            return str
          })
        }
      })
    },
    drawAllDetail() {
      // 统计所有分区详情leadtime报表
      queryDetailReportByAllDivision(this.params).then(res => {
        if (res) {
          // res[0]: x坐标名称
          // res[1]: 平均总耗时
          // res[2]: 分区平均总耗时
          // res[3]: 数据
          console.log('queryDetailReportByDivision:' + JSON.stringify(res))
          var nameObj = {}
          nameObj.xName = '分区'
          nameObj.yName = '耗时(' + this.unit + ')'
          nameObj.seriesName = '总耗时'
          if (res.length === 0) {
            this.drawChart(this.myChart, nameObj, null, null)
            return
          }
          nameObj.xNames = res[0]

          // 分区平均耗时
          this.devisionMap = res[2][0]

          var series = []
          this.nodeLegends.forEach((item, index) => {
            var serie = this.createStackSerie(item, res[index + 3])
            series.push(serie)
          })
          this.drawChart(this.myChart, nameObj, series, formatter => {
            var title = formatter[0].axisValue
            var str = ''
            formatter.forEach(item => {
              if (item.value !== undefined && item.value !== null) {
                str += item.marker + item.seriesName + ': ' + item.value.toFixed(2) + this.unit + '<br/>'
              } else {
                str += item.marker + item.seriesName + ': - ' + '<br/>'
              }
            })

            var total = this.devisionMap[title]
            if (total !== null && total > 0) {
              title += ': ' + total.toFixed(2) + this.unit + '<br/>'
            } else {
              title += ': - <br/>'
            }
            return title + str
          })
        }
      })
    },
    drawTotalByDivision() {
      // 根据分区统计总leadtime报表
      queryReportByDivision(this.params).then(res => {
        if (res) {
          var nameObj = {}
          nameObj.xName = '部门'
          nameObj.yName = '耗时(' + this.unit + ')'
          nameObj.seriesName = '总耗时'
          nameObj.legend = [nameObj.seriesName]
          nameObj.legendShow = false
          if (res.length === 0) {
            this.drawChart(this.myChart, nameObj, null, null)
            return
          }

          nameObj.xNames = res[0]
          var series = []
          var serie = this.createSerie(nameObj.seriesName, res[1])
          series.push(serie)
          this.drawChart(this.myChart, nameObj, series, formatter => {
            var title = formatter[0].axisValue + '部门' + '<br/>'
            var str = ''
            formatter.forEach(item => {
              if (item.value !== undefined && item.value !== null) {
                str += item.marker + item.seriesName + ': ' + item.value.toFixed(2) + this.unit + '<br/>'
              } else {
                str += item.marker + item.seriesName + ': - ' + '<br/>'
              }
            })
            return title + str
          })
        }
      })
    },
    drawDetailByDivision() {
      // 根据分区统计详情leadtime报表
      queryDetailReportByDivision(this.params).then(res => {
        if (res) {
          console.log('queryDetailReportByDivision:' + JSON.stringify(res))
          // res[0]: 部门(x轴坐标)
          // res[1]: 平均总耗时
          // res[2]: 部门平均总耗时
          // res[3]: 数据

          var nameObj = {}
          nameObj.xName = '部门'
          nameObj.yName = '耗时(' + this.unit + ')'
          nameObj.seriesName = '耗时(' + this.unit + ')'
          nameObj.legend = this.nodeLegends
          if (res.length === 0) {
            this.drawChart(this.myChart, nameObj, null, null)
            return
          }
          nameObj.xNames = res[0]
          var series = []
          this.nodeLegends.forEach((item, index) => {
            var serie = this.createStackSerie(item, res[index + 3])
            series.push(serie)
          })

          this.deptMap = res[2][0]

          this.drawChart(this.myChart, nameObj, series, formatter => {
            var title = formatter[0].axisValue + '部门'
            var str = ''
            formatter.forEach(item => {
              if (item.value !== undefined && item.value !== null) {
                str += item.marker + item.seriesName + ': ' + item.value.toFixed(2) + this.unit + '<br/>'
              } else {
                str += item.marker + item.seriesName + ': - ' + '<br/>'
              }
            })
            var total = this.deptMap[formatter[0].axisValue]
            if (total !== null && total > 0) {
              console.log('total:' + total)
              title += ': ' + parseFloat(total).toFixed(2) + this.unit + '<br/>'
            } else {
              title += ': - <br/>'
            }
            return title + str
          })
        }
      })
    },
    findDivision() { // 查询分区
      queryDivision().then(res => {
        if (res) {
          this.divisions = res
          this.params.division = res[0]
          this.divisions.forEach(item => {
            if (item !== 'All') {
              this.divisionLegends.push(item)
            }
          })
          this.toQuery()
        }
      })
    },
    divisionChanged() {
      this.params.deptNbr = null
      if (this.params.division === 'All') {
        this.deptSelectShow = false
      } else {
        this.deptSelectShow = true
      }
    },
    findDeptNbr() { // 查询分区部门
      if (this.params.division !== null && this.params.division !== '') {
        queryDeptNbrByDivision(this.params.division).then(res => {
          if (res) {
            this.deptNbrs = res
          }
        })
      } else {
        Message({
          message: '请选择分区!',
          type: 'warning',
          duration: 2 * 1000
        })
        this.deptNbrs = []
      }
    }
  }
}
</script>
